<template>
  <div className="app-container">
    <div style="background-color: #ffffff;">
      <div id="container"></div>
      <div class="search-container">
        <form id="search-form">
          <input type="text" id="search-input" placeholder="输入关键字搜索位置" />
          <button type="submit" id="search-button">搜索</button>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import AMapLoader from '@amap/amap-jsapi-loader';
import {ref,onMounted,watch} from "vue";
import throttle from "lodash/throttle";
const emit = defineEmits();
// const map = shallowRef(null);
const path = ref([]);
const props = defineProps({
  longitude: {
    type: Number,
    required: true
  },
  latitude: {
    type: Number,
    required: true
  }
});
const currentPosition = ref([props.longitude, props.latitude]);
function initMap() {
  window._AMapSecurityConfig = {
    securityJsCode: 'ca104dc0a3d2976ab480ce40690e16fb',
  }

  AMapLoader.load({
    key: "463ea9a2c9e8431aafed3c805c662e11", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins:['AMap.Geocoder'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
  }).then((AMap) => {
    const map = new AMap.Map("container", {  //设置地图容器id
      viewMode: "3D",    //是否为3D地图模式
      zoom: 16,           //初始化地图级别
      center:currentPosition.value, //初始化地图中心点位置
    });
    const marker = new AMap.Marker({
      position: currentPosition.value, // 标记点坐标
      map: map // 添加到地图
    });
    // 添加插件
    AMap.plugin(["AMap.Geolocation", "AMap.PlaceSearch"], function () {
      //异步同时加载多个插件
      // 添加地图插件
      map.addControl(new AMap.Geolocation()); // 定位当前位置

      const placeSearch = new AMap.PlaceSearch({
        city: '全国', // 搜索的城市
        pageSize: 10, // 单页显示结果条数
        pageIndex: 1, // 显示第几页
        map: map // 展示结果的地图实例
      });

      const searchForm = document.getElementById("search-form");
      const searchInput = document.getElementById('search-input');

      searchForm.addEventListener("submit", (event) => {
        event.preventDefault(); // 阻止表单默认提交行为
        const keyword = searchInput.value;
        throttledSearch(keyword); // 执行搜索逻辑
      });

      // 更新 initMap 中的 searchForm.addEventListener 块
      const throttledSearch = throttle((keyword) => {
        // 设置节流时间为3000毫秒（3秒）
        placeSearch.search(keyword);
        AMap.Event.addListener(placeSearch, 'markerClick', function (data) {
          let result = data
          let address = '';
          let province = '';
          let city = '';
          let district = '';
          let addr = '';
          let lng = result.event.lnglat.lng
          let lat = result.event.lnglat.lat
          const geocoder = new AMap.Geocoder();
          geocoder.getAddress(result.event.lnglat, function(status, result) {
            if (status === 'complete' && result.regeocode) {
              console.log(result.regeocode);
              // 获取格式化的地址信息
              address = result.regeocode.formattedAddress;
              province = result.regeocode.addressComponent.province;
              city = result.regeocode.addressComponent.city;
              district = result.regeocode.addressComponent.district;
              let strReplace = province + city + district;
              addr = address.replace(strReplace, '');
              // 发送坐标信息到父组件
              emit('coordinateClicked', {
                lng: lng,
                lat: lat,
                address: address,
                province: province,
                city: city,
                district: district, addr: addr
              });
            } else {
              console.error('逆地理编码失败');
            }
          });
          // let result = data
          // //经纬度
          // state.form.lng = result.event.lnglat.lng
          // state.form.lat = result.event.lnglat.lat
          // toGetAddress()
        });
      }, 5000);
    });
    // 单击
    map.on('click', (e) => {
      map.clearMap();
      let lng = 0;
      let lat = 0;
      let address = '';
      let province = '';
      let city = '';
      let district = '';
      let addr = '';
      const marker = new AMap.Marker({
        position: e.lnglat, // 标记点坐标
        map: map // 添加到地图
      });
      path.value.push(e.lnglat); // 将坐标添加到路径数组中
      lng = e.lnglat.lng;
      lat = e.lnglat.lat;
      // 逆地理编码
      const geocoder = new AMap.Geocoder();
      geocoder.getAddress(e.lnglat, function(status, result) {
        if (status === 'complete' && result.regeocode) {
          console.log(result.regeocode);
          // 获取格式化的地址信息
          address = result.regeocode.formattedAddress;
          province = result.regeocode.addressComponent.province;
          city = result.regeocode.addressComponent.city;
          district = result.regeocode.addressComponent.district;
          let strReplace = province + city + district;
          addr = address.replace(strReplace, '');
          // 发送坐标信息到父组件
          emit('coordinateClicked', {
            lng: lng,
            lat: lat,
            address: address,
            province: province,
            city: city,
            district: district, addr: addr
          });
        } else {
          console.error('逆地理编码失败');
        }
      });
    })
  }).catch(e => {
    console.log(e);
  })
}
function initSearchInput(){
  // 在组件重新加载时清空搜索输入字段
  const searchInput = document.getElementById('search-input');
  if (searchInput) {
    searchInput.value = '';
  }
}

watch(() => [props.longitude, props.latitude], (v) => {
  if (v[0] == null || v[1] == null){
    props.longitude = 118.8083;
    props.latitude = 31.8639;
  }
  currentPosition.value = [props.longitude,props.latitude]
  initMap();

}, { immediate: true });
onMounted(() => {
  initMap();
  initSearchInput();
});
initMap();
</script>

<style>
#container {
  padding: 0px;
  margin: 0px;
  width: 100%;
  height: 400px;
}

.search-container {
  position: absolute;
  top: 20px;
  left: 20px;
}

#search-input {
  padding: 8px;
  font-size: 16px;
  border: 1px solid #ccc;
  border-radius: 4px;
  margin-right: 8px;
}

#search-button {
  padding: 8px 16px;
  font-size: 16px;
  background-color: #007bff;
  color: #ffffff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

#search-button:hover {
  background-color: #0056b3;
}
</style>